﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using VelocityShop.Entities;
using VelocityShop.Data.SQLServer;

namespace VelocityShop.Data.AspNetCache
{

    public class AspNetCacheCatalogProvider:ICatalogProvider
    {

        public Catalog GetCatalog()
        {
            Cache cache = HttpContext.Current.Cache;

            //verify if catalog exists in cache
            Catalog cat;
            Object cacheItem;

            cacheItem = cache.Get("Catalog1");

            if (cacheItem == null)
            {
                //load catalog from DB
                Data.SQLServer.SQLServerCatalogProvider SQLServerCatalogProvider = new SQLServer.SQLServerCatalogProvider();

                cat = SQLServerCatalogProvider.GetCatalog();

                //put catalog in cache
                cache.Insert("Catalog1", cat);
            }
            else
            {
                cat = (Catalog)cacheItem;
            }

            return cat;

        }

        public IList<CatalogItem> GetItemsByCategoryId(string categoryId)
        {
            Cache cache = HttpContext.Current.Cache;
            IList<CatalogItem> itemsInCategory;

            itemsInCategory = (IList<CatalogItem>)cache.Get(categoryId);

            if (itemsInCategory == null)
            {
                //load catalog items from DB
                SQLServerCatalogProvider SQLServerCatalogProvider = new SQLServerCatalogProvider();

                itemsInCategory = SQLServerCatalogProvider.GetItemsByCategoryId(categoryId);

                cache.Insert(categoryId, itemsInCategory);

            }

            return itemsInCategory;
        }


        public void InsertCatalogItem(string categoryId, CatalogItem item)
        {
            Cache cache = HttpContext.Current.Cache;
            IList<CatalogItem> itemsInCategory;

            itemsInCategory = (IList<CatalogItem>)cache.Get(categoryId);
            itemsInCategory.Add(item); 

            cache.Insert(categoryId, itemsInCategory);
        }

        public IList<CatalogItem> GetItemsByTag(string categoryId, string tag)
        {
            throw new NotImplementedException();
        }

        public void InsertCatalogItem(string categoryId, CatalogItem item, string tags)
        {
            throw new NotImplementedException();
        }

    }
}